/*
 * Powered By xTOOLs
 * Dev by DuRisk@pactera.com
 * Copyright © 2009 - 2017 pactera.com. All rights reserved.
 *
 * Generated at 2017年12月25日 10:52:48
 *
 */

package com.pactera.jep.service.sys.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.pactera.jep.autoconfigure.web.controller.BaseRestController;
import com.pactera.jep.core.code.PermitType;
import com.pactera.jep.core.exception.ServiceException;
import com.pactera.jep.orm.Filter;
import com.pactera.jep.orm.Order;
import com.pactera.jep.orm.Page;
import com.pactera.jep.service.sys.dto.PermitTypeDto;
import com.pactera.jep.sys.code.AuthTargetType;
import com.pactera.jep.sys.code.AuthType;
import com.pactera.jep.sys.model.MetaAuthority;
import com.pactera.jep.sys.service.MetaAuthorityService;
import com.pactera.jep.sys.service.MetaRegionService;
import com.pactera.jep.web.code.WebCode;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value="元数据授权")
@RestController
@RequestMapping("/metaAuthority")
public class MetaAuthorityRestController extends BaseRestController<MetaAuthority> {
	private static Logger	logger	= LoggerFactory.getLogger(MetaAuthorityRestController.class);

	@Autowired
	private MetaAuthorityService	metaAuthorityService;
	
	@Autowired
	private MetaRegionService		metaRegionService;


	
	/**
	 * 为列表页面做数据准备
	 */
	@Override
	protected void prepareQuery(@ApiIgnore @RequestHeader("x-user-token") String token,
								Page<MetaAuthority> page, List<Filter> filters, List<Order> orders, HttpServletRequest request) {
		
		metaAuthorityService.query(page, filters, orders);
	}
	


	
	/**
	 * 保存
	 * @param metaAuthority
	 * @return
	 */
	@RequestMapping(value = "/save")
	@ResponseBody
	public Map<String, Object> save(MetaAuthority metaAuthority) {
		
		Map<String, Object> tips = new HashMap<String, Object>();
		
		Boolean isExist = metaAuthorityService.exists(metaAuthority.getAuthId());
		try 
		{
			if(isExist)
			{
				
				metaAuthorityService.update(metaAuthority);
			}
			else
			{
				metaAuthorityService.insert(metaAuthority);
			}
			
			tips.put(WebCode.SUCCESS, true);
			tips.put(WebCode.MSG, WebCode.SUCCESS_SAVE);
		}
		catch (ServiceException e) 
		{
			logger.info(e.getMessage());
			tips.put(WebCode.SUCCESS, false);
			tips.put(WebCode.MSG, WebCode.FAILURE_SAVE);
		}
		return tips;
	}
	
	/**
	 * 删除
	 * @param authId
	 * @return
	 */
	@RequestMapping(value = "/remove/{authId}")
	@ResponseBody
	public Map<String, Object> remove(@PathVariable String authId){
		
		Map<String, Object> tips = new HashMap<String, Object>();
		
		try 
		{
			metaAuthorityService.deleteByPrimaryKey(authId);
			tips.put(WebCode.SUCCESS, true);
			tips.put(WebCode.MSG, WebCode.SUCCESS_DELETE);
		} 
		catch (ServiceException e) 
		{
			logger.info(e.getMessage());
			tips.put(WebCode.SUCCESS, false);
			tips.put(WebCode.MSG, WebCode.FAILURE_DELETE);
		}
		
		return tips;
	}
	
	/**
	 * 验证提交的authId是否已经存在数据库中
	 * @param authId
	 * @return
	 */
	@RequestMapping(value = "/check", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map<String, Object> check(String authId){
		
		Map<String, Object> tips = new HashMap<String, Object>();
		
		boolean exist = metaAuthorityService.exists(authId);
		tips.put("valid", !exist);
		
		return tips;
	}
	
	/**
	 * 给角色赋上这些数据区域及其下的表的权限
	 * @param idStr 表ID
	 * @param roleCode 角色编号
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value="给角色赋上这些数据区域及其下的表的权限")
	@PostMapping(value =  "/saveRegionAuth")
	public Map<String, Object>  saveRegionAuth(@RequestBody JSONObject jsonObject) throws Exception {
		String idStr = jsonObject.getString("idStr");
		String roleCode = jsonObject.getString("roleCode");
		Map<String, Object> tips = new HashMap<String, Object>();
		try {
			metaAuthorityService.saveRegionAuth(roleCode, idStr);
			tips.put("success", true);
			tips.put("msg", "保存成功。");
		} catch (ServiceException se) {
			tips.put("success", false);
			tips.put("msg", "保存失败。");
			logger.error("系统出现异常：" + se.getMessage());
			throw se;
		}
		return tips;
	}
	
	/**
	 * 给角色赋上这些数据区域及其下的表的权限
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = { "/saveTableAuth" }, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object>  saveTableAuth(@RequestBody JSONObject jsonObject) throws Exception {
		String regionTableIds = jsonObject.getString("regionTableIds") ;
		String roleCode = jsonObject.getString("roleCode") ;
		String regionId = jsonObject.getString("regionId") ;
		Map<String, Object> tips = new HashMap<String, Object>();
		try {
			metaAuthorityService.saveTableAuth(roleCode, regionTableIds, regionId);
			tips.put("success", true);
			tips.put("msg", "保存成功。");
		} catch (ServiceException se) {
			tips.put("success", false);
			tips.put("msg", "保存失败。");
			logger.error("系统出现异常：" + se.getMessage());
			throw se;
		}
		return tips;
	}

	
	/**
	 *查看table表的数据权限
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "查看table表的数据权限")
	@PostMapping(value = "/permitTypes")
	public Map<String, Object> permitTypes(@RequestBody JSONObject jsonObject , HttpServletRequest request) throws Exception {
		String tableId = jsonObject.getString("tableId");
		String roleCode = jsonObject.getString("roleCode");
		String type = jsonObject.getString("type");
		Map<String, Object> data = new HashMap<>();
		List<PermitTypeDto> items = new ArrayList<PermitTypeDto>();
		
		/*只有当tableId和角色都不等于空的时候，才是正确的请求*/
		if(StringUtils.isNotBlank(tableId) && StringUtils.isNotBlank(roleCode)){
			/*当类型为表格的时候，获取数据权限*/
			if(AuthTargetType.TABLE.getValue().equals(type))
			{
				/*获取到实体类对应的数据权限定义*/
				PermitType[] permitTypes = PermitType.values();
				MetaAuthority authority = new MetaAuthority();
				authority.setAuthTarget(tableId);
				authority.setRoleCode(roleCode);
				authority.setAuthType(AuthType.DAK.getValue());
				authority = metaAuthorityService.get(authority);
				
				for(PermitType permitType : permitTypes){
					if(authority != null && permitType.getCode().equals(authority.getAuthData()))
					items.add(new PermitTypeDto(permitType.getName(), permitType.getCode(), true) );
					else if(!PermitType.FORBIDDEN.getCode().equals(permitType.getCode()))
					items.add(new PermitTypeDto(permitType.getName(), permitType.getCode(), false) );
				}
			}
		}
		data.put("total",items.size());
		data.put("rows", items);
		return data;
	}
	
	/**
	 * 保存数据权限到这个角色
	 * @param idStr 数据权限编码
	 * @param roleCode 角色编号
	 * @param tableId 表ID
	 * @return
	 */
	@ApiOperation(value = "保存数据权限到这个角色")
	@PostMapping(value = "/saveAuthorityBelongDAK")
	public Map<String, Object>  saveAuthorityBelongDAK(@RequestBody JSONObject jsonObject){
		String roleCode = jsonObject.getString("roleCode");
		String tableId = jsonObject.getString("tableId");
		String idStr = jsonObject.getString("idStr");
		Map<String, Object> tips = new HashMap<String, Object>();
		try {
			metaAuthorityService.saveAuthorityBelongDAK(roleCode, tableId, idStr);
			tips.put("success", true);
			tips.put("msg", "保存成功。");
		} catch (ServiceException se) {
			tips.put("success", false);
			tips.put("msg", "保存失败。");
			logger.error("系统出现异常：" + se.getMessage());
			throw se;
		}
		return tips;
	}
	
}